﻿using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.UserManagement.UserMamagements
{
    public class UserManagementController : BaseController
    {
        private UserManager<IdentityUser> UserManager { get; set; }

        public UserManagementController(UserManager<IdentityUser> userManager)
        {
            UserManager = userManager;
        }

        public ActionResult List(PagedRequestInput page)
        {
            var query = UserManager.Users.AsQueryable().Skip(page.SkipCount).Take(page.MaxResultCount);
            var users = query.ToList();
            var total = query.Count();
            var model = new PagedResult<IdentityUser>(total, users);
            return View(model);
        }

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Create(CreateInputModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Username);
                if (user != null)
                {
                    ModelState.AddModelError("Username", $"用户'{model.Username}'已存在");
                    return View(model);
                }
                if (!string.IsNullOrEmpty(model.Email))
                {
                    user = await UserManager.FindByEmailAsync(model.Email);
                    if (user != null)
                    {
                        ModelState.AddModelError("Email", $"邮箱'{model.Email}'已存在");
                        return View(model);
                    }
                }
                if (!string.IsNullOrEmpty(model.PhoneNumber))
                {
                    user = UserManager.Users.FirstOrDefault(t => t.PhoneNumber == model.PhoneNumber);
                    if (user != null)
                    {
                        ModelState.AddModelError("PhoneNumber", $"电话号码'{model.PhoneNumber}'已存在");
                        return View(model);
                    }
                }

                var identityUser = model.ToUser();
                identityUser.PasswordHash = UserManager.PasswordHasher.HashPassword(identityUser, model.Password);

                var createResult = await UserManager.CreateAsync(identityUser);

                if (createResult.Succeeded)
                {
                    return Success("新建用户成功", "/UserManagement/List", "编辑", "/UserManagement/Update/" + identityUser.Id);
                }
                else
                {
                    createResult.Errors.ToList().ForEach(t => ModelState.AddModelError("", t.Description));
                }
            }

            return View(model);
        }

        [HttpGet]
        public ActionResult Update(string id)
        {
            var model = UserManager.Users.AsNoTracking().Select(user => new UpdateInputModel
            {
                Id = user.Id,
                Username = user.UserName,
                PhoneNumber = user.PhoneNumber,
                Email = user.Email,
                Password = user.PasswordHash
            }).FirstOrDefault(t => t.Id == id);

            return View(model);
        }

        [HttpPost]
        public async Task<ActionResult> Update(UpdateInputModel model)
        {
            if (!ModelState.IsValid) return View(model);

            var user = UserManager.Users.FirstOrDefault(t => t.Id == model.Id);
            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "当前编辑的用户不存在");
                return View(model);
            }
            if (user.Email != model.Email)
            {
                if (UserManager.Users.AsNoTracking().Any(t => t.Email == model.Email))
                {
                    ModelState.AddModelError(string.Empty, $"邮箱'{model.Email}'已存在");
                    return View(model);
                }
            }
            if (user.PhoneNumber != model.PhoneNumber)
            {
                if (UserManager.Users.AsNoTracking().Any(t => t.PhoneNumber == model.PhoneNumber))
                {
                    ModelState.AddModelError(string.Empty, $"电话号码'{model.Email}'已存在");
                    return View(model);
                }
            }

            user.PhoneNumber = model.PhoneNumber;
            user.Email = model.Email;

            var updateResult = await UserManager.UpdateAsync(user);
            if (updateResult.Succeeded) return Success("编辑成功", "/userManagement/list", "重新编辑", "/userManagement/update/" + user.Id);

            updateResult.Errors.ToList().ForEach(t => ModelState.AddModelError(string.Empty, t.Description));
            return View(model);
        }
    }
}
